package com.keur.money.ui.main.fm

import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.UnderlineSpan
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.keur.money.R
import com.keur.money.app.MyApp
import com.keur.money.base.adapter.MullaOnItemChildClickListener
import com.keur.money.databinding.FmMullaRepayBinding
import com.keur.money.http.HttpHelper
import com.keur.money.mvp.MvpFm
import com.keur.money.ui.main.adapter.KeurRepayAdapter
import com.keur.money.ui.main.impl.KeurRepayPresenterImpl
import com.keur.money.ui.main.view.IKeurRepayView
import com.keur.money.ui.market.act.KeurRepayAct
import com.keur.money.ui.user.act.KeurUserLuckyDrawAct
import com.keur.money.ui.user.act.KeurUserMessageAct
import com.keur.money.utils.event.KeurEventData
import com.keur.money.utils.event.KeurEventType
import com.keur.money.utils.helper.KeurCustomConfigsHelper
import com.keur.money.utils.helper.SharedHelper
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/26 16:57
 * @Annotation：待还款
 */
class KeurRepayFm: MvpFm<IKeurRepayView, KeurRepayPresenterImpl>(),IKeurRepayView {
    private var _binding: FmMullaRepayBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )

    //待还款列表
    private var repayAdapter: KeurRepayAdapter? = null

    override fun createPresenter(): KeurRepayPresenterImpl {
        return KeurRepayPresenterImpl(context)
    }

    override fun getMullaRootView(inflater: LayoutInflater): View {
        _binding = FmMullaRepayBinding.inflate(inflater)
        return binding.root
    }

    override fun initMullaView() {
        setMullaTitleBarVisibility(View.VISIBLE)
        setMullaTitleBarColor(Color.parseColor("#FFFFFFFF"))
        setMullaBackBtnRes(R.mipmap.mulla_kefu_dialog_icon)
        setMullaRightBtnRes(R.mipmap.mulla_message_icon)
        setMullaTextTitle(getString(R.string.home_repayment_title))
        isInterceptBack(true)
        rootViewBinding.containerLayout.setBackgroundColor(Color.parseColor("#FFFFFFFF"))

        initMullaRefreshLayout()
        initMullaRecyclerView()

        val showTipsKey = getString(R.string.home_credit_score_result)
        val showTipsText = String.format(getString(R.string.home_credit_score_tips),showTipsKey)
        val spString = SpannableString(showTipsText)
        val start = showTipsText.indexOf(showTipsKey)
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#FFFFAC25")), start, showTipsText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        _binding?.textScoreTips?.text = spString

        val showText = String.format(getString(R.string.home_repayment_empty),getString(R.string.home_repayment_apply))
        val startIndex = showText.indexOf(getString(R.string.home_repayment_apply))
        val emptySpannableString = SpannableString(showText)
        emptySpannableString.setSpan(ForegroundColorSpan(Color.parseColor("#FF8027FF")), startIndex, showText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        emptySpannableString.setSpan(UnderlineSpan(), startIndex, showText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        _binding?.textEmpty?.text = emptySpannableString
    }

    override fun initMullaListener() {
        rootViewBinding.ivBaseBack.setOnClickListener {
            showMullaKefuDialog("Repayment Page")
            HttpHelper.addKeurEventAction(KeurEventType.CLICK.KEUR_CLICK_CUSTOMER,"Repayment Page")
        }
        rootViewBinding.ivFun.setOnClickListener {
            onIntent(KeurUserMessageAct::class.java)
        }
        //抽奖
        _binding?.luckydrawLayout?.btnGo?.setOnClickListener {
            onIntent(KeurUserLuckyDrawAct::class.java)
        }
        // Apply Now 、 Repay Now
        _binding?.textEmpty?.setOnClickListener {
            MyApp.app.publisher.publish(KeurEventData(KeurEventData.TYPE.KEUR_SHOW_PRODUCTS))
            MyApp.app.publisher.publish(KeurEventData(KeurEventData.TYPE.KEUR_SHOW_HOME))
        }
    }

    override fun initMullaData() {
        //牌照信息
        val licenseInfo = KeurCustomConfigsHelper.getMullaLicenseInfo()
        if (licenseInfo == null){
            _binding?.licenseLayout?.removeAllViews()
            _binding?.licenseLayout?.visibility = View.GONE
        } else {
            _binding?.licenseLayout?.removeAllViews()
            _binding?.licenseLayout?.addView(licenseView())
            _binding?.licenseLayout?.visibility = View.VISIBLE
        }
        presenter.loadMullaRepayListAction()
        HttpHelper.addKeurEventAction(KeurEventType.PAGE.KEUR_PAGE_REPAY_START)
    }

    /* 初始化刷新 */
    private fun initMullaRefreshLayout() {
        //禁止加载
        _binding?.refreshLayout?.setEnableLoadMore(false)
        _binding?.refreshLayout?.setEnableAutoLoadMore(false)
        _binding?.refreshLayout?.setOnRefreshListener {
            MyApp.app.publisher.publish(KeurEventData(KeurEventData.TYPE.KEUR_PRODUCT_REFRESH))
        }
        _binding?.refreshLayout?.setOnLoadMoreListener {
            _binding?.refreshLayout?.finishLoadMore()
        }
    }

    /**
     * 初始化产品列表
     */
    private fun initMullaRecyclerView() {
        _binding?.recyclerView?.layoutManager = LinearLayoutManager(context)
        repayAdapter = KeurRepayAdapter(_binding?.recyclerView)
        _binding?.recyclerView?.adapter = repayAdapter
        _binding?.recyclerView?.itemAnimator = DefaultItemAnimator()
        repayAdapter?.setOnItemChildClickListener(MullaOnItemChildClickListener { _, childView, position ->
            val item = repayAdapter?.getItem(position)
            when (childView.id) {
                R.id.itemLayout -> {//点击Item
                }

                R.id.detailsLayout -> {//查看详情
                    item?.let {
                        val pName = it.optString("product")
                        val pToken = it.optString("token")
                        KeurRepayAct.start(requireContext(), pName, pToken)
                    }
                }
            }
        })
    }

    /**
     * 设置待还款列表
     */
    override fun showMullaRepayList(repayList: ArrayList<JSONObject>) {
        hideMullaLoading()
        if (isNewUser()){
            _binding?.scoreTipsLayout?.visibility = View.GONE
        } else {
            _binding?.scoreTipsLayout?.visibility = View.VISIBLE
        }

        if (repayList.size == 0){
            _binding?.recyclerView?.visibility = View.GONE
            _binding?.emptyLayout?.visibility = View.VISIBLE
            return
        }
        _binding?.recyclerView?.visibility = View.VISIBLE
        _binding?.emptyLayout?.visibility = View.GONE

        repayAdapter?.data = repayList
    }

    override fun hideMullaLoading() {
        super.hideMullaLoading()
        _binding?.refreshLayout?.finishRefresh()
    }

    override fun onKeurEvent(event: KeurEventData) {
        super.onKeurEvent(event)
        when(event.eventType){
            KeurEventData.TYPE.KEUR_PRODUCT_REFRESHED -> {//刷新产品列表
                presenter.loadMullaRepayListAction()
            }
            KeurEventData.TYPE.KEUR_PRODUCT_FINISHED -> {
                hideMullaLoading()
            }
            else -> {

            }
        }
    }

    /**
     * 是否是新用户
     */
    private fun isNewUser(): Boolean{
        val dataString = SharedHelper.getKeurSPString(SharedHelper.KEUR_SPKEY.KEUR_PROCESS)
        if (dataString.isEmpty()){
            return true
        }
        val obj = JSONObject(dataString)
        if (!obj.has("userType")){
            return true
        }
        return obj.optString("userType") == "NEW"
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addKeurEventAction(KeurEventType.PAGE.KEUR_PAGE_REPAY_END)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}